<template>
  <div id="home">
    <!-- 用户登录页 -->
    <section class="bgsign">
      <!-- 背景图 -->
      <div class="sign">
        <div class="homepage">
          <img src="@/assets/two/new_logo.png" />
        </div>
      </div>
      <div class="verification">
        <div class="cation">
          <div class="phone_wrap">
            <img class="icon_phone" src="@/assets/two/icon_phone.png" />
            <input
              type="tel"
              pattern="[0-9]*"
              maxlength="11"
              oninput="value=value.replace(/[^\d]/g,'')"
              placeholder="请输入手机号码"
              v-model="phone"
              @blur="checkPhone()"
              @focus="checkph()"
              :class="{ errBorder: errMsg == 1 }"
            />
            <img
              class="clear-icon"
              src="@/assets/two/clear-icon.png"
              v-show="isShowPhone"
              @click="clearPhone"
            />
          </div>
          <span class="tips" v-show="errMsg1">*手机号格式错误</span>
          <span class="tips" v-show="empty1">*请输入手机号</span>

          <div class="box">
            <img class="icon_verify" src="@/assets/two/icon_verify.png" />
            <input
              type="number"
              v-model="code"
              oninput="if(value.length>6) value = value.slice(0,6)"
              @blur="checkCode()"
              @focus="checkPhone()"
              :class="{ errBorder: errMsg == 2 }"
              placeholder="请输入验证码"
              @keyup.enter.native="phone_login()"
              ref="phoneCodeInput"
            />
            <img
              class="clear-icon"
              style="margin-right:0.4rem;"
              src="@/assets/two/clear-icon.png"
              v-show="isShowCode"
              @click="clearCode"
            />
            <!-- disabled="tapclick" -->
            <button @click="get_code()">
              <span>{{ time }}</span>
            </button>
          </div>

          <span class="tips" v-show="errMsg2">* {{ msg }}</span>
          <span class="tips" v-show="empty2">*请输入验证码</span>
          <button
            id="loginBtn"
            :class="{ active: phone.length == 11 && code.length == 6 }"
            @click="phone_login()"
          >登录</button>
        </div>
      </div>
    </section>
  </div>
</template>
<script>
export default {
  name: '',
  components: {},
  data() {
    return {
      phone: '',
      code: '',
      time: '获取验证码',
      errMsg: 0, //0:通过    1:手机号格式不对 2：验证码格式不对
      photo: '',
      vipLevel: 0,
      person_message: null,
      tapclick: false, //获取验证是否可以点击
      cancel03: null,
      cancel04: null,
      cancel05: null,
      empty1: false,
      errMsg1: false,
      empty2: false,
      errMsg2: false,
      msg: '', //验证码错误/次数过多稍后再试
      isShowPhone: false, //最开始不显示清除按钮
      isShowCode: false,
      invitecode: this.urlPms.invitecode ? this.urlPms.invitecode : '', //邀请码
      wxCode:'',
    };
  },
  computed: {},
  watch: {},
  created() {
    this.initUser();
    if (localStorage.getItem('photo')) {
      this.photo = localStorage.getItem('photo');
    } else {
      this.photo = '';
    }
  },
  methods: {
    //点击清除手机号和验证码
    clearPhone() {
      this.phone = '';
    },
    clearCode() {
      this.code = '';
      this.errMsg2 = false;
      this.empty2 = true;
    },
    initUser() {
      let uid = localStorage.getItem('user_id');

      let isSMSLogin = this.$route.query.sms;
      // 微信授权登录
      // 微信浏览器打开
      if (this.$isWX && !isSMSLogin) {
        // 微信授权登录
        this.wxCode = this.GetParam().code;
        if (!uid) {
          if (this.wxCode) {
            this.getWXInfo();
          } else {
            this.wx(); //授权
          }
        } else {
          this.get_person().then(level => {
            //此种情况是针对解绑微信之后，user_id失效做处理
            if (level == 1006 || level == 1010) {
              // location.reload();
              // this.wx();
            } else {
              this.$getPower(level);
            }
          });
        }
      } else {
        if (uid) {
          this.get_person().then(level => {
            this.$getPower(level).then(() => {
            });
          });
        }
      }
    },
    wx() {
      // 获取code
      let APP_ID = 'wx3f218079525514d2';
      let SCOPE = 'snsapi_userinfo';
      let STATE = 'default';
      const local = location.href; // 获
      location.href =
        'https://open.weixin.qq.com/connect/oauth2/authorize' +
        '?appid=' +
        APP_ID +
        '&redirect_uri=' +
        encodeURIComponent(local) +
        '&response_type=code&scope=' +
        SCOPE +
        '&state=' +
        STATE +
        '#wechat_redirect' +
        '&connect_redirect=1'; //防止二次加载
    },
    GetParam() {
      var url = location.search;
      this.winUrl = url;
      var theRequest = new Object();
      if (url.indexOf('?') != -1) {
        var str = url.substr(1);
        var strs = str.split('&');
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
        }
      }
      return theRequest;
    },
    setUserInfo(res){  //缓存用户基本信息
      if(res.data.data.accountId){
        localStorage.setItem('user_id', res.data.data.accountId);
      }
      localStorage.setItem('photo', res.data.data.headImgUrl);
      localStorage.setItem('vipLevel', res.data.data.vipLevel);
      localStorage.setItem('phone', res.data.data.phone);
      localStorage.setItem('nickName', res.data.data.nickName);
      localStorage.setItem('autoVipType', res.data.data.autoVipType);
      localStorage.setItem('vipDuration', res.data.data.duration);
      // 会员到期时间
      if (res.data.data.vipLevel == '0') {
        localStorage.setItem('vipEndTime1', 0);
      } else {
        localStorage.setItem('vipEndTime1', res.data.data.vipEndTime1);
      }
    },
    getWXInfo() {
      return new Promise((resolve, reject) => {
        this.$axios({
          method: 'get',
          url: '/api/customer/wechatoauthlogin',
          params: {
            Code: this.wxCode
          }
        })
          .then(res => {
            if (res.data.code == 0) {
              this.user_id = res.data.data.accountId;
              this.photo = res.data.data.headImgUrl;
              console.log(res);
              this.setUserInfo(res);
              // resolve(res.data.data.vipLevel);
              this.$router.replace({ path: '/' });
              // location.href = '/'; //首页
              // location.reload();
            } else if (res.data.code == -7 || res.data.code == -5) {
              //-5未注册，-7未绑定手机号
              let msg = res.data.msg;
              let rPms = {
                path: '/loginweixin',
                query: { msg }
              };
              if (this.invitecode) {
                rPms.query.invitecode = this.invitecode;
              }
              this.$router.push(rPms);
            } else if (res.data.code == -6) {
              //-6用户状态错误，---留在登录页
              // let rPms = {
              //   path: '/login',
              //   query: {}
              // };
              // if (this.invitecode) {
              //   rPms.query.invitecode = this.invitecode;
              // }
              // this.$router.push(rPms);
            } else if (res.data.code == -3) {
              //-3token解析错误
              this.wx(); //重新获取
            }
          })
          .catch(err => {
            reject(err);
            console.log(err);
          });
      });
    },
    //   获取用户信息
    get_person() {
      return new Promise((resolve, reject) => {
        let that = this;
        this.$axios(
          {
            method: 'get',
            url: '/api/customer/getperson' //是否登录
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel05) that.cancel05();
              that.cancel05 = c;
            })
          }
        )
          .then(res => {
            if (res.data.code == 0) {
              this.person_message = res.data.data;
              this.setUserInfo(res);
              resolve(res.data.data.vipLevel);
            }
            // if (res.data.code == 1006) {
            //   this.$router.push('/login');
            // }
          })
          .catch(error => {
            reject(error);
            console.log(error);
          });
      });
      let that = this;
    },
    //   验证手机号(失去) ///  验证码获取焦点
    checkPhone() {
      setTimeout(() => {
        this.isShowPhone = false;
      }, 0);
      this.isShowCode = true;
      const str = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
      if (!str.test(this.phone)) {
        this.empty1 = false; //请输入
        this.errMsg1 = true; //格式错误
      }
      if (this.phone.length === 0) {
        this.empty1 = true;
        this.errMsg1 = false;
      }
      if (str.test(this.phone) && this.phone.length != 0) {
        this.empty1 = false;
        this.errMsg1 = false;
      }
      if (this.code.length === 0 || this.code.length != 6 || this.code.length != 0) {
        this.empty2 = false;
        this.errMsg2 = false;
      }
    },
    // 验证验证码格式（失去焦点）
    checkCode() {
      setTimeout(() => {
        this.isShowCode = false;
      }, 0);
      if (this.code.length === 0) {
        this.empty2 = true;
        this.errMsg2 = false;
      } else if (this.code.length != 6) {
        this.empty2 = false;
        this.errMsg2 = true;
      }
    },
    // 手机号获取到焦点
    checkph() {
      this.empty1 = false;
      this.errMsg1 = false;
      this.isShowPhone = true;
    },
    // 获取验证码
    get_code(codeType) {
      let that = this;
      if (this.time != '重新获取' && this.time != '获取验证码') {
        that.tapclick = true;
        return false;
      }
      const str = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
      if (this.phone.length === 0) {
        this.empty1 = true;
        this.errMsg1 = false;
        return false;
      }
      if (!str.test(this.phone)) {
        this.empty1 = false; //请输入
        this.errMsg1 = true; //格式错误
        return false;
      }
      if (str.test(this.phone) && this.phone.length != 0) {
        // 手机号满足条件发送验证码
        this.empty1 = false;
        this.errMsg1 = false;
        this.errMsg = 0;
      }
      if (codeType == 1) {
        that.$axios
          .get('/api/customer/VerifyMobile', {
            params: {
              mobile: that.phone
            }
          })
          .then(res => {
            if (res.data.code == 0) {
              that.getsmsCode();
            } else if (res.data.code == 1) {
              that.errMsg2 = false;
              this.errMsg2 = true;
              this.empty1 = false;
              this.empty2 = false;
              that.errMsg = 3;
              return false;
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        that.getsmsCode();
      }
      this.$refs.phoneCodeInput.focus();
    },
    getsmsCode() {
      //重新获取验证
      let that = this;
      let temp = 60;
      this.time = temp + 's';
      this.loopTime = setInterval(() => {
        temp -= 1;
        this.time = temp + 's';
        if (temp == 0) {
          clearInterval(this.loopTime);
          this.time = '重新获取';
          that.tapclick = true;
        } else {
          that.tapclick = false;
        }
      }, 1000);
      //   获取验证码
      this.$axios(
        {
          method: 'get',
          url: '/api/customer/getsms',
          params: {
            mobile: that.phone
          }
        },
        {
          cancelToken: new that.$axios.CancelToken(function executor(c) {
            if (that.cancel03) that.cancel03();
            that.cancel03 = c;
          })
        }
      )
        .then(response => {
          this.$toast(response.data.msg);
          if (response.data.code == 1001) {
            this.$toast(response.data.msg);
          }
          if (response.data.code == 0) {
            that.tapclick = true;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    phone_login() {
      // this.$toast(this.msg);
      //点击登录
      window.localStorage.clear();
      if (!(this.phone.length == 11)) {
        return (this.errMsg2 = false);
      }
      if (!(this.code.length == 6)) {
        // return false
        return (this.errMsg2 = false);
      }
      let that = this;
      let invitecode = this.$route.query.invitecode;
      invitecode = invitecode ? invitecode : '';
      this.$axios
        .post(
          '/api/customer/smslogin',
          {
            Mobile: that.phone,
            Code: that.code,
            InviteCode: invitecode
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel04) that.cancel04();
              that.cancel04 = c;
            })
          }
        )
        .then(response => {
          if (response.data.code == 0) {
            // 存储 id
            localStorage.setItem('user_id', response.data.data.accountId);

            if(response.data.data.loginType == 2 && invitecode){
              localStorage.setItem('isInvitationUser', 1);  //是否为被邀请注册用户
            }
            this.dialog = false;
            this.get_person().then(level => {
              this.$getPower(level);
              location.replace('/');
            });
            // if(response.data.data.loginType == 2){
            //   localStorage.setItem('isPopSiginSuccess', 1);
            // }
            // this.$router.replace({ path: '/' }); //首页
          } else if (response.data.code == 1) {
            // 手机号
            this.errMsg2 = true;
            this.empty1 = false;
            this.empty2 = false;
          } else {
            // 验证码
            this.errMsg2 = true;
            this.empty1 = false;
            this.empty2 = false;
          }
          if (response.data.code == 2) {
            this.msg = response.data.msg;
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};
</script>
<style scoped lang="less">
// 登陆
#home {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  *,
  *:before,
  *:after {
    box-sizing: inherit;
  }
  .van-nav-bar__title {
    font-size: 0.426667rem;
    font-weight: 600;
    color: #222;
  }
  //   登录
  .bgsign {
    width: 100%;
    .active {
      //提交按钮
      background-color: #fd7f2c !important;
      color: #fff !important;
    }
    .sign {
      width: 100%;
      height: 6.04rem;
      background: url(../../assets/two/new_bg.png) no-repeat 0 -1.933333rem;
      background-size: 100% 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .homepage {
        width: 1.88rem;
        height: 1.88rem;
        background: #fff;
        box-shadow: 0px 0px 19px 5px rgba(0, 0, 0, 0.1);
        border-radius: 0.4rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .verification {
      width: 100%;
      .cation {
        width: 100%;
        padding: 0 0.813333rem;
        .phone_wrap,
        .box {
          padding-bottom: 0.4rem;
          border-bottom: 1px solid #e5e5e5;
          display: flex;
          align-items: center;
          position: relative;
          .icon_phone,
          .icon_verify {
            vertical-align: middle;
            width: 0.333333rem;
            height: 0.44rem;
            margin-right: 0.386667rem;
          }
          .clear-icon {
            width: 0.413333rem;
            height: 0.413333rem;
          }
        }
        input[type='number'],
        input[type='tel'] {
          outline: none;
          border: 0;
          font-size: 0.4rem;
          width: 100%;
          height: 100%;
          background-color: transparent;
        }

        .tips {
          //提示手机号错误
          display: block;
          font-size: 0.32rem;
          line-height: 1.093rem;
          height: 1.093rem;
          letter-spacing: 0px;
          color: #ff0000;
        }
        .box {
          margin-top: 0.706667rem;
          > button {
            outline: none;
            width: 4.506667rem;
            font-size: 0.4rem;
            color: #ee7d2f;
            border: 0;
            background: transparent;
            border-left: 1px solid #e5e5e5;
          }
        }
        #loginBtn {
          outline: none;
          border: 0;
          width: 100%;
          margin-top: 1.773333rem;
          height: 1.226667rem;
          background-color: #b5b5b5;
          border-radius: 0.266667rem;
          font-size: 0.4rem;
          color: #fff;
        }
      }
    }
  }
}
</style>
